import React, {useEffect} from 'react';
import {StyleSheet, View} from 'react-native';
import {CommentType, ScreensParamList} from 'types';
import {StackNavigationProp} from '@react-navigation/stack';
import {useDispatch, useSelector} from 'react-redux';
import actions from 'reduxState/actions';
import VirScroll, {VirgetParamType} from 'components/VirScroll';
import DetailComment from './Details/DetailComment';
import qs from 'qs';
import {selectEventDetail} from 'reduxState/selectors';
import {get, ResponseType} from 'utils/request';

type WebScreenNavigationProp = StackNavigationProp<ScreensParamList>;

export interface Props {
  navigation: WebScreenNavigationProp;
}
const limit = 10;

export function creatGetComments(eventId: number | undefined) {
  return async function ({offset}: VirgetParamType) {
    const {data}: ResponseType = await get(
      `/events/${eventId}/comments?${qs.stringify({
        offset,
        limit,
      })}`,
    );
    return {
      list: data.comments.sort((pre: CommentType, after: CommentType) => {
        const res =
          new Date(after.createdAt || '').getTime() -
          new Date(pre.createdAt || '').getTime();
        return res;
      }),
      hasMore: data.hasMore,
    };
  };
}
function Comments({navigation}: Props) {
  const dispatch = useDispatch();

  const detailInfo = useSelector(selectEventDetail);
  const getData = creatGetComments(detailInfo?.id);
  useEffect(() => {
    const unsubscribe = navigation.addListener('tabPress', (e) => {
      // 设置detailsTab激活
      dispatch(actions.setActiveTab('Comments'));
    });

    return unsubscribe;
  }, []);
  return (
    <>
      <View style={styles.container}>
        <VirScroll
          freshForce={detailInfo}
          getDataFn={getData}
          keyExtractor={(item) => String(item.id)}
          renderItem={DetailComment}
        />
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    backgroundColor: '#FAF9FC',
  },
  line: {
    marginTop: 24,
    marginBottom: 16,
  },
});
export default Comments;
